package cn.lysj.framework.api.controller;

import cn.lysj.framework.api.base.ApiContent;
import cn.lysj.framework.common.domain.User;
import cn.lysj.framework.common.exception.MyException;
import cn.lysj.framework.common.utils.http.HttpUtil;
import cn.lysj.framework.common.utils.web.ParamUtil;
import cn.lysj.framework.common.utils.web.Resp;
import cn.lysj.framework.customer.util.WxAuzLoginUtil;
import cn.lysj.framework.verify.domain.OffAcctOpenidVerify;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Map;

import static cn.lysj.framework.customer.util.WxAuzLoginUtil.GET_WEB_ACCESS_TOKEN_URL;

/**
 * @ Author ：drj.
 * @ Date  ：Created in 10:52 2019/2/21
 * @ Description:消息推送模块绑定商户openid
 **/
@RestController
@RequestMapping("/api/v1/message")
@Slf4j
public class ApiMessageController extends ApiContent {

    private String redictUrl = "https://diet.lingyundata.com/static/bind/index.html"; //state1代表微信授权跳转首页

    //获取openId
    @GetMapping("/get_official_account_openid")
    public void getOpenId() throws IOException {
        String code = request.getParameter("code");
        if (ParamUtil.isBlank(code)) {
            throw new MyException("未知错误");
        }
        //获取openid
        StringBuilder sb = new StringBuilder();
        sb.append("appid=").append(WxAuzLoginUtil.wx_app_id).append("&secret=").append(WxAuzLoginUtil.wx_app_secret).append("&code=").append(code).append("&grant_type=authorization_code");
        String tokenJson = HttpUtil.sendGet(GET_WEB_ACCESS_TOKEN_URL, sb.toString());
        Gson gson = new Gson();
        Map<String, String> map = gson.fromJson(tokenJson, WxAuzLoginUtil.type);
        String openId = map.get("openid");
        String accessToken = map.get("access_token");
        if (ParamUtil.isBlank(openId) || ParamUtil.isBlank(accessToken)) {
            throw new MyException("授权失败");
        }
        //将accessToken 跟openid保存用户绑定校验
        OffAcctOpenidVerify offAcctOpenidVerify = new OffAcctOpenidVerify();
        offAcctOpenidVerify.setAccessToken(accessToken);
        offAcctOpenidVerify.setOpenid(openId);
        offAcctOpenidVerifyService.getRepository().save(offAcctOpenidVerify);
        log.info(redictUrl+"?accessToken=" + accessToken);
        response.sendRedirect(redictUrl+"?accessToken=" + accessToken);
    }

    /*
     * @author drj
     * @date 2019-02-21 11:09
     * @Description ：绑定openid
     */
    @PostMapping("bind_user_official_account_openid")
    public Resp bindUserOpenId(String username, String password, String accessToken) {
        //校验用户名
        if (ParamUtil.isBlank(username)) {
            return new Resp(Resp.PARAM_ERROR, "请输入用户名");
        }
        User user = userService.getRepository().findByUsername(username);
        if (ParamUtil.isBlank(user)) {
            return new Resp(Resp.PARAM_ERROR, "用户名错误");
        }
        //校验密码
        if (!(new BCryptPasswordEncoder().matches(password, user.getPassword()))) {
            return new Resp(Resp.PARAM_ERROR, "密码错误");
        }
        if (ParamUtil.isBlank(accessToken)) {
            return new Resp(Resp.PARAM_ERROR, "未知错误");
        }
        //校验accessToken
        OffAcctOpenidVerify offAcctOpenidVerify = offAcctOpenidVerifyService.getRepository().findByAccessToken(accessToken);
        if (ParamUtil.isBlank(offAcctOpenidVerify)) {
            return new Resp("未知错误");
        }
        //保存openid信息
        user.setOfficialAccountOpenid(offAcctOpenidVerify.getOpenid());
        userService.getRepository().save(user);
        return new Resp("操作成功");
    }

}
